package com.itheima.day27;

import com.itheima.dao.UserMapper;
import com.itheima.bean.User;
import com.itheima.utils.MybatisUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        //设置请求和响应为utf-8
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        //获得提交的用户名和密码
        String userName = req.getParameter("username");
        String passWord = req.getParameter("password");
        //验证输入的信息
        SqlSession session = MybatisUtil.getSession();
        UserMapper mapper = session.getMapper(UserMapper.class);
        User user = mapper.login(userName, passWord);
        //设置网页编码utf-8
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if(user == null){
            System.out.println("用户登录失败");
            //没有找到登录失败  弹出登录失败的信息 并且跳转到登录页面
            writer.println("<script>");
            writer.println("alert('登录失败')");
            //弹出登录失败的信息 并且跳转到登录页面
            writer.print("location.href='login.html'");
            writer.println("</script>");
        }else {
            //登录成功 弹出消息提示
            writer.println("<script>");
            writer.println("alert('登录成功')");
            //跳转到登录成功的页面
            writer.print("location.href='https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F1011%2F05141G13226%2F1F514113226-6-1200.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1647507713&t=2f3e3df5f454967c6bfa0b03960ebd68';");
            writer.println("</script>");
            System.out.println("用户:" + userName + "登录成功");
        }
        session.close();
    }
}













































